package com.example.community.add;

import com.example.community.dao.UsersDao;
import com.example.community.model.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(urlPatterns = "/userAddServlet")
public class UserAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/userManager/userAdd.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        String loginname = req.getParameter("loginname");
        String password = req.getParameter("password");
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String tel = req.getParameter("tel");

        try {
            UsersDao usersDao = new UsersDao();

            Users users = usersDao.fandById(Integer.parseInt(uid));
            if (users == null){
                Users user = new Users();
                user.setUsNo(Integer.parseInt(uid));
                user.setUsAccount(loginname);
                user.setUsPwd(password);
                user.setUsName(username);
                user.setUsSex(sex);
                user.setUsTel(tel);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date parse = sdf.parse(birthday);
                user.setUsBirthday(parse);


                Integer insert = usersDao.insert(user);
                if (insert == 1){
                    resp.getWriter().write("true");
                }else {
                    resp.getWriter().write("false");
                }
            }else {
                resp.getWriter().write("qita");
            }

        } catch (ParseException e) {
            e.printStackTrace();
            resp.getWriter().write("false");
        }
    }
}
